from TTS.api import TTS
from pydub import AudioSegment

# 指定中文模型名称
model_name = "tts_models/zh-CN/baker/tacotron2-DDC-GST"
# 指定声码器名称
vocoder_name = "vocoder_models/zh-CN/baker/hifigan_v2"

# 创建 TTS 对象，同时指定模型和声码器
tts = TTS(model_name=model_name, vocoder_path=vocoder_name, gpu = True)

# 遍历 chapter01.txt 到 chapter80.txt
for i in range(1, 81):
    # 格式化文件名
    chapter_num = str(i).zfill(2)  # 将数字转换为两位字符串，如 1 转换为 01
    file_path = f"chapter{chapter_num}.txt"
    output_file = f"chapter{chapter_num}.wav"

    try:
        # 用于存储当前章节的所有音频片段
        audio_segments = []

        # 读取文本文件内容
        with open(file_path, 'r', encoding='utf-8') as file:
            text  = file.read()
            tts.tts_to_file(text=text, file_path=output_file)
            print(f"语音合成完成，音频文件已保存为 {output_file}")

    except FileNotFoundError:
        print(f"错误：未找到文件 {file_path}")
    except Exception as e:
        print(f"处理 {file_path} 时发生未知错误：{e}")
